package com.diyizu.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diyizu.youdianda.common.PageResult;
import com.diyizu.youdianda.common.R;
import com.diyizu.youdianda.dto.YddArticleDto;
import com.diyizu.youdianda.entity.YddArticle;
import com.diyizu.youdianda.entity.YddUser;
import com.diyizu.youdianda.entity.YddUserData;
import com.diyizu.youdianda.service.YddArticleService;
import com.diyizu.youdianda.service.YddUserDataService;
import com.diyizu.youdianda.service.YddUserService;
import com.diyizu.youdianda.util.JwtUtils;
import com.diyizu.youdianda.util.UserID;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddUserDataService yddUserDataService;

    @GetMapping("/userDataList")
    public R userDataList(HttpServletRequest httpServletRequest,@RequestParam Map map) {
        String token = httpServletRequest.getHeader("token");
        int useId=0;
        if (JwtUtils.verifyToken(token)) {
            Claims claims = JwtUtils.getClaims(token);
            useId = (int) claims.get("id");
        }
        String currentId = String.valueOf(useId);
       // UserID.setCurrentId(String.valueOf(useId));

        String page = (String) map.get("page");
        String limit = (String) map.get("limit");
        String type = (String) map.get("type");
  //      String currentId = UserID.getCurrentId();
        LambdaQueryWrapper<YddUserData> dataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dataLambdaQueryWrapper.eq(YddUserData::getUserId, currentId);
        dataLambdaQueryWrapper.eq(YddUserData::getType, type);
        List<YddUserData> list = yddUserDataService.list(dataLambdaQueryWrapper);
        ArrayList<Integer> articleId = new ArrayList<>();
        if (list == null || list.size() == 0) {
            HashMap<String, Map> m = new HashMap<>();
            HashMap<String,Object > h = new HashMap<>();
            ArrayList<Object> l = new ArrayList<>();
            h.put("count",0);
            h.put("data",l);
            m.put("list",h);
            return R.success(m);
        }
        for (YddUserData yddUserData : list) {
            articleId.add(yddUserData.getArticleId());
        }
        Page<YddArticle> yddArticlePage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.in(YddArticle::getId, articleId);
        yddArticleService.page(yddArticlePage, lqw);
        PageResult pageResult = new PageResult();
        pageResult.setData(yddArticlePage.getRecords());
        pageResult.setPageSize(yddArticlePage.getSize());
        pageResult.setCurrentPage(yddArticlePage.getCurrent());
        pageResult.setCount(yddArticlePage.getTotal());
        pageResult.setTotalPages(yddArticlePage.getPages());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list", pageResult);
        return R.success(hashMap);
    }

    //我的文章
    @GetMapping("/myArticle")
    public R<YddArticleDto> myArticle(Integer page, Integer limit) {
        log.info("用户相关-我的文章：page=" + page + ";limit=" + limit);
        YddArticleDto yddArticleDto = yddArticleService.myArticle(page, limit);
        return R.success(yddArticleDto);
    }

    //发布文章
    @PostMapping("/addArticle")
    public R<String> addArticle(@RequestBody YddArticle yddArticle) {
        log.info("用户相关-发布文章：yddArticle=" + yddArticle);
        yddArticleService.save(yddArticle);
        return R.success("发布成功");
    }

    //删除文章(草稿箱的可以删除，已发布的没找到删除)
    @GetMapping("/delArticle")
    public R<String> delArticle(Integer id) {
        log.info("用户相关-删除文章：id=" + id);
        yddArticleService.removeById(id);
        return R.success("删除成功");
    }

    //修改文章(发布、修改)
    @PostMapping("/editArticle")
    public R<String> editArticle(@RequestBody YddArticle yddArticle){
        log.info("修改请求：yddArticle="+yddArticle);
        yddArticleService.updateById(yddArticle);
        return R.success("更新成功");
    }

    @GetMapping("/getUserInfo")
    public R getUserInfo(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        long id;
        if (JwtUtils.verifyToken(token)) {
            Claims claims = JwtUtils.getClaims(token);
            id = (Integer) claims.get("id");
        } else {
            return R.error("用户信息已过期");
        }
        YddUser yddUser = yddUserService.getById(id);


        Map<String, Object> map = new HashMap<>();
        map.put("userInfo", yddUser);

        QueryWrapper<YddArticle> articleQw = new QueryWrapper<>();
        articleQw.eq("author", yddUser.getUsername());
        int articleNum = yddArticleService.count(articleQw);
        map.put("articleNum", articleNum);

        QueryWrapper<YddUserData> zanQw = new QueryWrapper<>();
        zanQw.eq("user_id", yddUser.getId());
        zanQw.eq("type", 2);
        int zanNum = yddUserDataService.count(zanQw);
        map.put("zanNum", zanNum);

        QueryWrapper<YddUserData> collectQw = new QueryWrapper<>();
        collectQw.eq("user_id", yddUser.getId());
        collectQw.eq("type", 1);
        int collectNum = yddUserDataService.count(collectQw);
        map.put("collectNum", collectNum);

        return R.success(map);

    }

    @PostMapping("/update")
    public R update(@RequestBody YddUser yddUser) {
        yddUserService.updateById(yddUser);
        return R.success("修改成功");
    }

    @GetMapping("/userDataHandle")
    public R userDataHandle(HttpServletRequest httpServletRequest, Integer type, String action, Integer article_id) {
        if ("add".equals(action)) {
            yddArticleService.addData(httpServletRequest,type, article_id);
        }
        if ("del".equals(action)) {
            yddArticleService.delData(httpServletRequest,type, article_id);
        }
        return R.success(null);
    }
}
